package cn.sinothk.hussars.parent;

import android.app.Activity;
import android.content.Intent
import com.sinothk.android.utils.XUtils
import com.sinothk.helper.image.compress.ImageCompress
import com.sinothk.image.selector.PhotoPickerActivity

import com.sinothk.image.selector.SelectModel;
import com.sinothk.image.selector.intent.PhotoPickerIntent;
import java.io.File

abstract class ImageSelectBaseActivity : EventBusTitleBaseActivity() {

    protected fun gotoSelectImg(
        activity: Activity,
        rCode: Int,
        selectMode: SelectModel,
        needCamera: Boolean
    ) {
        requestCode = rCode
        val intent = PhotoPickerIntent(activity)
        intent.setSelectModel(selectMode)//  SelectModel.SINGLE
        intent.setShowCamera(
            needCamera,
            this.application.packageName
        ) // 是否显示拍照， 默认false com.sinothk.living
        startActivityForResult(intent, requestCode)
    }

    private var requestCode = 300
    private var imageFilePath = ""

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (data == null) {
            return
        }

        // 图片选择
        if (requestCode == requestCode) {
            if (resultCode == Activity.RESULT_OK) {
                val filePathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT)

                if (filePathList != null && filePathList.size > 0) {
                    imageFilePath = filePathList[0]
//                    hasImage = true
                    val oldFile = File(imageFilePath)
                    val fileSize = oldFile.length()

                    val mb = 0.5 * 1024 * 1024
                    if (fileSize > mb) {// 大于0.5MB压缩
                        ImageCompress.execute(
                            imageFilePath
                        ) { path, pathArr ->
                            if (path != null) {

                                val newPath: String = path
                                val newFile = File(newPath)
                                if (newFile.length() > 0) {
                                    upLoad(newPath, oldFile.name)
                                } else {
                                    XUtils.toast().show("压缩图片为空")
                                }
                            } else {
                                XUtils.toast().show("图片压缩失败")
                            }
                        }
                    } else {
                        if (oldFile.length() > 0) {
                            upLoad(imageFilePath, oldFile.name)
                        } else {
                            XUtils.toast().show("选择的文件太小")
                        }
                    }
                } else {
                    tip("选择图片失败")
                }
            }
            return
        }
    }

    abstract fun upLoad(filePath: String, fileName: String)

}
